package com.shanghaionstar.mro.presenter;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.entity.RequestType;
import com.onstar.cn.vehicle.result.PollingResult;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.mro.iview.IMroView;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.remote.manager.RemoteOperateManager;
import com.shanghaionstar.remote.manager.RemoteOperateValidateHelper;
import com.shanghaionstar.remote.model.CommandStatus;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.remote.service.RemoteService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.DateFormatUtil;
import com.shanghaionstar.utils.FinalConfigParams;

import org.json.JSONException;
import org.json.JSONObject;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Rengui Lu on 2016/8/23.
 */
public class MroPresenter extends BasePresenter {
    private IMroView mMroView;
    private BaseActivity context;
    private RemoteService remoteService;
    private NavService navService;
    private Subscription subscription;
    private Subscription pollingSubscription;
    private Subscription pinSubscription;
    private Subscription initAlertgSubscription;

    MrOActivity.OnMroOperationCallbackListener operationCallbackListener;
    RemoteOperateValidateHelper helper;


    public MroPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        mMroView = (IMroView) view;
        context = (BaseActivity) view.onActivity();
        remoteService = new RemoteService(context);
        super.setServiceProvider(remoteService);
//        registPollingSub();
        /**
         * alert 30s init
         */
        initAlertParam();
        helper = new RemoteOperateValidateHelper(context);
    }


    public void remoteControl(String request, MrOActivity.OnMroOperationCallbackListener operationCallbackListener) {
//        if (!BusinessUtil.isServiceEntitlement(activity, Constants.ENTITLEMENT_M07REMOTE_CONTROL)) {
//            operationCallbackListener.onRemoteControlCallbackListener(true, activity.getString(R.string.UC009_MSG007));
//            return;
//        }
        this.operationCallbackListener = operationCallbackListener;
        /**
         * 需要弹出框提示用户买包
         */
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M07REMOTE_CONTROL, context, true)) {
            operationCallbackListener.onRemoteControlCallbackListener(true, BusinessUtil.getCheckPackageRightString(Constants.ENTITLEMENT_M07REMOTE_CONTROL, context));
            return;
        }
        RemoteCommandsType remoteCommandsType = null;
        RequestType requestType = null;
        FeatureEnum featureEnum = null;
        if ("LockDoors".equals(request)) {
            requestType = RequestType.LockDoorsRequest;
            remoteCommandsType = RemoteCommandsType.COMMANDS_LOCK_DOOR;
            featureEnum = FeatureEnum.LOCKDOOR;
        } else if ("UnlockDoors".equals(request)) {
            requestType = RequestType.UnlockDoorsRequest;
            remoteCommandsType = RemoteCommandsType.COMMANDS_UNLOCK_DOOR;
            featureEnum = FeatureEnum.UNLOCKDOOR;
        } else if ("RemoteStart".equals(request)) {
            requestType = RequestType.RemoteStartRequest;
            remoteCommandsType = RemoteCommandsType.COMMANDS_START;
            featureEnum = FeatureEnum.START;
        } else if ("CancelStart".equals(request)) {
            requestType = RequestType.RemoteStopRequest;
            remoteCommandsType = RemoteCommandsType.COMMANDS_CANCEL_START;
            featureEnum = FeatureEnum.CANCELSTART;
        } else if ("FlashLights".equals(request) ||
                "Horn".equals(request) ||
                "FlashHorn".equals(request)) {
            requestType = RequestType.VehicleAlertRequest;
            remoteCommandsType = RemoteCommandsType.COMMANDS_ALERT;
            featureEnum = FeatureEnum.ALERT;
        } else {
            /**Couldn't happen**/
            operationCallbackListener.onRemoteControlCallbackListener(true, "Unknown request" + request);
            return;
        }
        if (!BusinessUtil.isServiceFeature(featureEnum.value(), context)) {
            operationCallbackListener.onRemoteControlCallbackListener(true, context.getString(R.string.UC009_MSG008));
            return;
        }
        if (BusinessUtil.checkInProgressCommand(context, null, false)) {
            operationCallbackListener.onRemoteControlCallbackListener(true, context.getString(R.string.UC009_MSG005));
            return;
        }
        doCommand(remoteCommandsType);
    }

    protected PreferencesUtls preferences = PreferencesUtls.getInstance(OnstarApplication.getApplication());


//    public void registLoginAndOutShowView() {
//        new LoginUtil().loginAndOutShowView(context, this);
//    }

    private void initAlertParam() {
        initAlertgSubscription = remoteService.initAlertParams().subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        try {
                            ApplicationUtil.getInstance().setAlertDuration(Integer.parseInt(new JSONObject(s).getString("duration")));
                        } catch (JSONException e) {
                            ApplicationUtil.getInstance().setAlertDuration( ApplicationUtil.ALERT_DURATION_DEF);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        ApplicationUtil.getInstance().setAlertDuration( ApplicationUtil.ALERT_DURATION_DEF);
                    }
                });
    }


    public void command(RemoteModel remoteModel){
        RemoteOperateManager.getInstance().init(context).exeRemote(remoteModel.getRemoteCommandsType());
    }

    /**
     * 操作入口
     *
     * @param remoteCommandsType
     */
    public void doCommand(RemoteCommandsType remoteCommandsType) {
        if (helper.validateCommandType(mMroView)) {
            if (mMroView != null) {
                mMroView.onReponseSuccess(new RemoteModel.Builder()
                        .setRemoteCommandsType(remoteCommandsType)
                        .setAlertMsg(context.getString(helper.getAlertDialogByType(remoteCommandsType.value())))
                        .setCommandStatus(CommandStatus.START).create());
            }
        }
    }



    /**
     * 自动触发或弹pin码
     * call before start;
     *
     * @param
     */

    public void onAutoSendPin(RemoteModel remoteModel){
        operationCallbackListener.onRemoteControlCallbackListener(true, String.format(context.getString(R.string.UC009_MSG006),
                getRequestStringByType(remoteModel.getRemoteCommandsType())));
    }



    private String getRequestStringByType(RemoteCommandsType requestType) {
        String str = "";
        switch (requestType) {
            case COMMANDS_LOCK_DOOR:
                str = context.getResources().getString(R.string.lock_hint);
                break;
            case COMMANDS_UNLOCK_DOOR:
                str = context.getResources().getString(R.string.unlock_hint);
                break;
            case COMMANDS_START:
                str = context.getResources().getString(R.string.start_hint);
                break;
            case COMMANDS_CANCEL_START:
                str = context.getResources().getString(R.string.stop_hint);
                break;
            case COMMANDS_ALERT:
                str = context.getResources().getString(R.string.alert_hint);
                break;
            default:
                break;
        }
        return str;
    }



    public void unRegisterSubscriber() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        if (pinSubscription != null && !pinSubscription.isUnsubscribed()) {
            pinSubscription.unsubscribe();
        }
        if (pollingSubscription != null && !pollingSubscription.isUnsubscribed()) {
            pollingSubscription.unsubscribe();
        }

        if (initAlertgSubscription != null && !initAlertgSubscription.isUnsubscribed()) {
            initAlertgSubscription.unsubscribe();
        }
    }

    public boolean isRemoteCommand(String type){
        return helper.isRemoteCommand(type);
    }


    public void updateView(PollingResult result) {
        RemoteCommandsType commandsType = RemoteCommandsType.fromValue(result.getRequestType());
        if (commandsType == null) return;
        StringBuffer commandResult = new StringBuffer();
        int commandId = 0;
        int resultId = 0;
        switch (commandsType) {
            case COMMANDS_UNLOCK_DOOR:
                commandId = R.string.remote_unlock;
                commandResult.append(context.getString(R.string.remote_unlock));
                break;
            case COMMANDS_LOCK_DOOR:
                commandId = R.string.remote_lock;
                commandResult.append(context.getString(R.string.remote_lock));
                break;
            case COMMANDS_START:
                commandId = R.string.remote_start;
                commandResult.append(context.getString(R.string.remote_start));
                break;
            case COMMANDS_CANCEL_START:
                commandId = R.string.remote_cancel_start;
                commandResult.append(context.getString(R.string.remote_cancel_start));
                break;
            case COMMANDS_ALERT:
                commandId = R.string.remote_alarm;
                commandResult.append(context.getString(R.string.remote_alarm));
                break;
        }
        if (RequestStatus.Success.getStringValue().equals(result.getRequestStatus())) {
            resultId = R.string.remote_command_success;
            commandResult.append(context.getString(R.string.remote_command_success));
        } else {
            resultId = R.string.remote_command_fail;
            commandResult.append(context.getString(R.string.remote_command_fail));
        }
        String formatCommandResult = "";
        if (!CommonUtil.isNull(result.getCompleteTime())) {
            formatCommandResult = DateFormatUtil.formatHHmm(result.getCompleteTime(), 8);
        }

        preferences.putString(FinalConfigParams.LAST_COMMAND_TYPE + "_" + ApplicationUtil.getInstance().getVin(),
                commandId + "," + resultId);
        preferences.putString(FinalConfigParams.LAST_COMMAND_TIME + "_" + ApplicationUtil.getInstance().getVin(),formatCommandResult);
        if (mMroView != null) {
            mMroView.showCommandResult(result);
        }

    }




    public void saveHis(RemoteModel remoteModel){
        if (remoteModel.getRemoteCommandsType() == RemoteCommandsType.COMMANDS_NAV_DESTINATION ||
                remoteModel.getRemoteCommandsType() == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
            helper.saveHistoryToSql(remoteModel.requestId, remoteModel.poiItemInfo, null, true);
            //将下发历史保存到历史记录中
            helper.saveSearchHistory(remoteModel.poiItemInfo);
        }
        if (mMroView != null) {
            mMroView.showCommandLoading(true);
        }
    }

    public void sendTbtOrOdd(PoiItemInfo poiItemInfo) {
        helper.sendTbtOrOdd(poiItemInfo);
//        RemoteModel model = helper.getRemoteModel();
//        model.poiItemInfo = poiItemInfo;
//        if(helper.validateTbtOrOdd(poiItemInfo,model.getRemoteCommandsType())){
//            RemoteOperateManager.getInstance().init(context).exeRemote(model.getRemoteCommandsType(),poiItemInfo);
//        }
    }


}
